package demo02_work_queue;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeoutException;

/**
 * @Description 工作队列模式的消息消费者：模拟 WorkQueue 工作队列的模式，需要先启动多个 Consumer 消费者，然后再启动生产者，查看消息是否被负载消费！
 * @Author shihan
 * @Date 2020/12/20 10:54
 * @Version 1.0
 */
public class WQConsumer {

    public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException, IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri("amqp://root:123456@192.168.66.129:5672/%2f");

        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        // 声明一个队列
        channel.queueDeclare(WQProducer.QUEUE_NAME,true,false,false,null);
        // 监听队列中的消息，进行消费
        channel.basicConsume(WQProducer.QUEUE_NAME,true, new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                // 监听到消息队列中有消息，触发的回调函数
                System.out.println("消费者监听到消息：" + new String(message.getBody(),"utf-8"));
            }
        }, new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {
                // 消息被拒绝的处理. do nothing ...
            }
        });

        // 消费者不去关闭连接，因为要让 连接和通道 都保持连通的状态，可以进行持续的消息监听

    }

}
